using System;
using System.IO;
using MongoDB.Driver;
using MongoDB.Driver.GridFS;

namespace MongoScienceDAL.Core
{
    public class ScienceVersionedFileRepository : IScienceVersionedFileRepository
    {
        private readonly MongoGridFS _mongoGridFS;

        public ScienceVersionedFileRepository(IDataSource dataSource)
        {
            _mongoGridFS = dataSource.Database.GridFS;
        }

        public VersionedFile Upload(Stream fileStream, string filename, string uploader, string version)
        {
            var fileInfo = _mongoGridFS.Upload(fileStream, filename);

            return new VersionedFile
                                    {
                                        FileId = fileInfo.Id.AsObjectId,
                                        Filename = filename,
                                        Size = fileInfo.Length,
                                        UploadedBy = uploader,
                                        UploadedOn = DateTime.Now,
                                        Version = version
                                    };
        }

        public Stream Download(VersionedFile file)
        {
            var fileInfo = _mongoGridFS.FindOneById(file.FileId);
            return fileInfo.OpenRead(); 
        }

        public void Delete(VersionedFile file)
        {
            _mongoGridFS.DeleteById(file.FileId);
        }
    }
}